//
//  RBImageBannerView.m
//  RBDemoProj
//
//  Created by Lan on 2019/1/14.
//  Copyright © 2019年 SummerTea. All rights reserved.
//

#import "RBImageBannerView.h"
#import "RBBannerView.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import "UIImageView+RBAdd.h"

@interface RBImageBannerView()<RBBannerViewDelegate>

@property(nonatomic, strong) RBBannerView *bannerView;
@property(nonatomic, strong) UIPageControl *pageControl;

@end

@implementation RBImageBannerView

#pragma mark - RBBannerViewDelegate

- (NSInteger)numberOfItemsInBannerView:(RBBannerView *)bannerView
{
    return self.dataSource.count;
}

- (void)bannerView:(RBBannerView *)bannerView willSetupView:(UIView *)view withIndex:(NSInteger)index
{
    if ([view isKindOfClass:[UIImageView class]])
    {
        UIImageView *imgView = (UIImageView *)view;
        id data = self.dataSource[index];
        if ([data isKindOfClass:[UIImage class]])
        {
            imgView.image = (UIImage *)data;
        }
        else if ([data isKindOfClass:[NSString class]])
        {
            [imgView setImageWithUrl:(NSString *)data placeHolder:nil];
        }
    }
}

- (void)bannerView:(RBBannerView *)bannerView scrollToIndex:(CGFloat)index
{
    self.pageControl.currentPage = (NSInteger)roundf(index);
}

- (void)bannerView:(RBBannerView *)bannerView didSelectView:(UIView *)view withIndex:(NSInteger)index
{
    if (self.selectBlock)
    {
        self.selectBlock(index);
    }
}

#pragma mark - Setter

- (void)setDataSource:(NSArray *)dataSource
{
    _dataSource = dataSource;
    [self.bannerView reloadData];
    self.pageControl.hidden = dataSource.count <= 1;
    self.pageControl.numberOfPages = dataSource.count;
}

#pragma mark - Getter

- (RBBannerView *)bannerView
{
    if (!_bannerView)
    {
        self.bannerView = ({
            RBBannerView *view = [RBBannerView new];
            view.deleagte = self;
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            view;
        });
    }
    return _bannerView;
}

- (UIPageControl *)pageControl
{
    if (!_pageControl)
    {
        self.pageControl = ({
            UIPageControl *view = [UIPageControl new];
            view.currentPageIndicatorTintColor = [RBThemeConfig themeColor];
            view.pageIndicatorTintColor = [RBThemeConfig bgGrayColor];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.height.mas_equalTo(20);
            }];
            view;
        });
    }
    return _pageControl;
}

@end
